#include "nlohmann_json_utils.h"

#include <fstream>
#include <iostream>

using namespace std;

void json_write(std::string path)
{
    nlohmann::json root;
    root["name"]  = "张三";
    root["age"]   = 18;
    root["total"] = 247.0;

#if 0
    root["scores"] = {89.5, 90.0, 67.5};
#else
    nlohmann::json scores = nlohmann::json::array();
    scores.push_back(89.5);
    scores.push_back(90.5);
    scores.push_back(67.5);
    root["scores"] = scores;
#endif

    std::string jsonstr = root.dump();
    // 写入文件
    ofstream file(path);
    if (!file.is_open()) {
        std::cout << "文件打开失败" << std::endl;
        exit(EXIT_FAILURE);
    }
    file.write(jsonstr.c_str(), jsonstr.length());
    file.close();
}

void json_read(std::string path)
{
    nlohmann::json root = loadJsonFile(path);

    std::cout << "name  : " << getJsonValue<std::string>(root, "name") << std::endl;
    std::cout << "age   : " << root.at("age") << std::endl;
    std::cout << "total : " << root["total"].get<double>() << std::endl;
    std::cout << "scores: " << root["scores"] << std::endl;
    for (int i = 0; i < root["scores"].size(); i++) {
        std::cout << "score : " << root["scores"][i] << std::endl;
    }
}

void json_test(std::string path)
{
    nlohmann::json root = loadJsonFile(path);
    std::cout << "json: " << root.dump() << std::endl;
    std::string name = getJsonValue<std::string>(root, "name");
    std::cout << "name: " << name << std::endl;
}

int main(int argc, char *argv[])
{
    json_write("nlohmann.json");
    json_test("nlohmann.json");
    json_read("nlohmann.json");

    return 0;
}